package com.lancoo.znbkxx.teacher.ui.activity

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext.Companion.COURSE_CLASSID
import com.lancoo.znbkxx.teacher.Ext.Companion.GLOBAL_GRADE
import com.lancoo.znbkxx.teacher.Ext.Companion.KEY
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.SearchListAdapter
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.base.SharedPreferencesHelper
import com.lancoo.znbkxx.teacher.databinding.ActivitySearchHistroyBinding
import com.lancoo.znbkxx.teacher.model.data.Paper
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.widget.SearchPopupWindow

/**
 * @author : Admin
 * @date   : 2019/7/31 15:18
 * @desc   :
 */
class SearchHistoryActivity : BaseVMActivity<PaperViewModel, ActivitySearchHistroyBinding>(),
    TextView.OnEditorActionListener, TextWatcher, BaseQuickAdapter.OnItemClickListener {
    private val dataList = mutableListOf<Paper>()
    private lateinit var adapter: SearchListAdapter
    private var mLastSearchTime: Long = 0
    private val paperList = mutableListOf<Paper>()
    private val sPopupWindow by lazy { SearchPopupWindow(this) }
    private lateinit var rvSearch: RecyclerView
    val layer by lazy { intent.getStringExtra("layer") }
    override fun providerVMClass(): Class<PaperViewModel>? {
        return PaperViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.activity_search_histroy
    }

    override fun initView() {
        viewModel.pageNo.value = 1
        viewModel.pageSize.value = 10
        binding.tvCancel.setOnClickListener { finish() }
        binding.edtSearch.apply {
            requestFocus()
            setOnEditorActionListener(this@SearchHistoryActivity)
            addTextChangedListener(this@SearchHistoryActivity)
        }
        sPopupWindow.setOnDismissListener { binding.viewSearch.visibility = GONE }
        rvSearch = sPopupWindow.contentView.findViewById(R.id.rv_search)
        initRecycleView()
    }

    private fun initRecycleView() {
        adapter = SearchListAdapter(R.layout.item_search_list, paperList)
        val manager = LinearLayoutManager(this)
        adapter.onItemClickListener = this
        rvSearch.layoutManager = manager
        rvSearch.adapter = adapter
    }

    override fun afterTextChanged(editable: Editable?) {
        if (editable.toString().isNotEmpty()) {
            searchPaperByKeyword(editable.toString())
        }
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onEditorAction(p0: TextView?, p1: Int, p2: KeyEvent?): Boolean {
        if (p1 == EditorInfo.IME_ACTION_SEARCH) {
            val intent = Intent(this, SearchActivity::class.java)
            intent.putExtra("keywords", binding.edtSearch.text.toString().trim())
            intent.putExtra("layer", layer)
            startActivity(intent)
            finish()
            return true
        }
        return false
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        sPopupWindow.dismiss()
        val intent = Intent(this, SearchActivity::class.java)
        intent.putExtra("keywords", dataList[position].PaperName)
        intent.putExtra("layer", layer)
        startActivity(intent)
        finish()
    }

    private fun searchPaperByKeyword(keyWords: String) {
        if (System.currentTimeMillis() - mLastSearchTime > 1000) {
            mLastSearchTime = System.currentTimeMillis()
        } else {
            return
        }
        if (!TextUtils.isEmpty(keyWords)) {
            viewModel.searchInfo.value = keyWords
            initSearch()
        }
    }

    private fun initSearch() {
        viewModel.getPaperForMobileSearch(
            CurrentUser.UserID,
            CurrentUser.Token,
            CurrentUser.SchoolID,
            COURSE_CLASSID,
            layer,
            viewModel.searchInfo.value!!,
            0L,
            0L,
            "0",
            viewModel.pageNo.value!!,
            viewModel.pageSize.value!!
        )
    }

    override fun startObserve() {
        viewModel.mSearchPaperList.observe(this, Observer { it ->
            if (sPopupWindow.isShowing) {
                sPopupWindow.dismiss()
            }
            dataList.clear()
            dataList.addAll(it.List)
            val isAgreePermissions = SharedPreferencesHelper.getBoolean("isAgreePermissions", false)
            if (dataList.size == 0 || !isAgreePermissions) {
                binding.ivEmpty.visibility = VISIBLE
                adapter.setNewData(null)
            } else {
                binding.ivEmpty.visibility = GONE
                adapter.setNewData(dataList)
                sPopupWindow.showAsDropDown(binding.linearLayout, 0, 0)
                binding.viewSearch.visibility = VISIBLE
            }
        })
    }
}